import mqtt from "mqtt";
import store from '../../store/index'
// import Emitter from "../mitt/event";
export default {
	MQTT_SERVER: "ws://47.111.173.131:8083/mqtt", //ws的端口是8083  TCP端口是1883
	MQTT_CONFIG: {
		username: "hikari",
		password: "hikari123",
		clientId: "WEB_" + new Date().getTime(),
		keepAlive: 60,
		cleanSession: true,
		clear: true,
	},
	mTopicList: [],
	mClient: null,
	mConState: 0, //0 未连接 1:正在连接 2:连接成功

	init() {
		if (store.state.topicList) {
			this.mTopicList = JSON.parse(store.state.topicList);
		}
		setInterval(() => {
			if (this.mTopicList.length > 0 && this.mConState == 2) {
				for (var item of this.mTopicList) {
					this.subTopic(item);
				}
				this.mTopicList = [];
			}
		}, 1000);
	},

	handleCon() {
		if (this.mConState != 0) return;
		console.log("==handleCon==");
		this.mClient = mqtt.connect(this.MQTT_SERVER, this.MQTT_CONFIG);
		// mqtt连接
		this.mClient.on("connect", (e) => {
			console.log(e, "mqtt连接成功！");
			this.mConState = 2;
		});

		// 消息处理
		this.mClient.on("message", (topic, message) => {
			// console.log("收到消息", topic, message);
			var uint8_msg = new Uint8Array(message);
			var msg = String.fromCharCode.apply(null, uint8_msg);
			console.log(topic);
			console.log(msg);
			// this.$mitt.emit("MQTT-MSG", JSON.parse(msg));
		});

		// 断线重连
		this.mClient.on("reconnect", (error) => {
			console.log("正在重连：", new Date().getTime(), error);
			this.mConState = 1;
		});

		// 连接失败
		this.mClient.on("error", (err) => {
			console.log("mqtt连接失败！{}", err);
			this.mClient.end();
			this.mConState = 0;
		});
	},

	/**
	 * 【通用】发布话题
	 *
	 */

	pubTopic(topic, msg) {
		console.log("=======pubTopic=====" + topic);
		if (!this.mClient) return;
		this.mClient.publish(topic, msg, 1, (err) => {
			if (!err) {
				console.log("发布成功！");
			} else {
				console.log("发布失败！", err);
			}
		});
	},

	/**
	 * 【通用】订阅话题
	 */
	subTopic(topic) {
		if (!this.mClient) return;
		console.log("=======subTopic=====" + topic);
		this.mClient.subscribe(topic, 1, (err) => {
			if (!err) {
				console.log("订阅成功！");
			} else {
				console.log("订阅失败！", err);
			}
		});
	},
	/**
 * 【通用】订阅话题
 */
	addTopic(topic) {
		this.mTopicList.push(topic);
	},


	closeCon() {
		this.mConState = 0;
		this.mClient.end();
	},
};
